//
//  ZZCBuyUbiController.m
//  ZZC-Finance
//
//  Created by mac on 2017/5/23.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "ZZCBuyUbiController.h"
#import "ZZCBuyDetailsController.h"
#import "WXApi.h"

//支付宝相关
#import <AlipaySDK/AlipaySDK.h>
#import "Order.h"
#import "RSADataSigner.h"

static NSString *privateKey = @"MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCBDyrw+3eltPa2+YIbUaUeBbXOr8hTgUphdL0aIVBzZQchHmpcWj/MdhGb6/RvKYxSPck27WVeDMO3MwYUOI0uERI+AZtP7ehQCqBELgtr11n9cqkhc6TaTOeb0T04f09qPkXQ5GXPmBl2EWGy9+ZUgWvqMOzIb2dfLvSLiNjA53Y3ye0t3dt+uQvuSLGHUMVipDLWpvE9t+pIJyGT04DfOUsXT/8xwjaWhu3irvVga7UvDcI7MMjcMHADtl350qdGkfaPTPl3BtDR+ICikN2p2EJC82TGbr8DHiWB5IkET83/tU/oU7R3D7xSKbBNH4lfBYcit/kdVSlPSRiAMrVNAgMBAAECggEAezx0kLBPS9hFTetrJZMMzGI/fSG1dKec0vqaJ/1vyQDLkgBtJ8q16RNFNVJWkl9mMpH1NZHynaAqsyDxyRVHGpoKhVMbb3OJxgSfjPs6xLtanv2CKwM2g420C8H9Z5mJx7W3DQVLgrOGfIuUc0Tsl/0Ngw88yxg16Vn5AdSmxWvkSlquyNZIsBGhyHBQRzcjueQEH11oZtnxe7434f0iso0oetsGY3m+cXad1Q4gUpq1lWKwWUPpls+v/ZR1/hRWhGUep7+QrNfmkXml9nDX95LB3B9QL2caxfJlyW1xJLVcV7DR3uRlM06ATzeGODswiFrvsLLk+PVK05pa4TBnMQKBgQDBw3hmOtYzRn8qR6nDPI/NkLjAO8TRPi/CVP+eGhu2Kqnzf7d6DENcT7N75oaKV2KXN0+c6PyY0rzpoABEwkWBKmc1ynSAdjWKDjKScUBvZxLQPzxABLYwiVg0xKA4toAMmzGFlUE+nZ/k8s03v8hcfp4SkouolLSUEfblkBSkSwKBgQCqg0dLqv7QmBJGeLbApBkztF588vFotutdJ9QH4mvEKU+YfO0QG5AGqBE3+rOlTRfw890Uy2uY/qms2pZKXHkmmRFUJb0QFOSBY0/jwK0Axh9rgbCUqz2xnoUUDS/qMI9+UPCZJ5pByIj5/V0SCd+8/OT1s6/NH2MfzFiBRQ+dxwKBgFXkCyvt6uOh3V7lk3grEWfDPlJgbDeAxHT1brYrxprywJFizPc6FmYGIn7Kylrqr5Zue0kH8mjgCcPaHCRepabDICs1Cn2jaMpAzuQhdbmsTCep0FBkhkpvp30EqC1boNl1tfcMGXbjMmyvwI504iE2M2XyNhxNhtqYOAS84JmPAoGAe+Ll6hRTDztuC8WpAk44AVkLTb01qN8+InDNnOzlX6CkNCaQFyPvgOabnBCKdY+N1YNZHcKuanqczPoEOAL4AxMzg+/nbcfAPkHpyZA0IlvQeEvCAEJqkKKcDfWG2qBtoVktdhlP+nu5CekLtg92f9k+gUYMdPxZCMFvjHyg3AECgYByuaRn0vRTSxygRpap904yEBjKJKlgcyhU17xckNaogHXxUvXk2iwb2m8x2aHaqgE7pqD2uYbDLH9zs6OIHoubH4l9zLqeRuY18/o4fyvuiFTGgCV+Tc4710Hvb7lmIFSqHxh+emOXaQaGlw3UUxR+NmStyFrj+hSHa+7eR/KlnQ==";

@interface ZZCBuyUbiController ()
//购买数量
@property (weak, nonatomic) IBOutlet UITextField *buyCountTextField;
@property (nonatomic, strong) GRBkeyTextField * safeTextField;
@property (nonatomic, strong) GRBkeyTextField * safeInputTextField;
@property (strong, nonatomic) ZZCMenuView *menuView;
@property (nonatomic, strong) GRBsafeKeyBoard * board;
@property (weak, nonatomic) IBOutlet UIButton *buyWayBtn;
@property (weak, nonatomic) IBOutlet UIView *buyWayView;
@property (assign, nonatomic) NSInteger arrIndex;//支付方式选取
@property (strong, nonatomic) NSDictionary *dicc;
@property (copy ,nonatomic) NSString *response;
@end

@implementation ZZCBuyUbiController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"购买U币";
    IQKeyboardManager *iq = [IQKeyboardManager sharedManager];
    iq.enableAutoToolbar = NO;
}

- (BOOL)isNumber {
    NSString *regex =@"[0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if (![pred evaluateWithObject:self.buyCountTextField.text]) {
        return NO;
    }
    return YES;
}


//确认
- (IBAction)confirmClick {
    if (_buyCountTextField.text == nil||[_buyCountTextField.text intValue] < 1) {
        [SVProgressHUD showInfoWithStatus:@"请输入具体数量(不小于1)"];
        return;
    }

    if ([_buyWayBtn.titleLabel.text isEqualToString:@"支付宝"]) {
        [self buy];
    } else {
        [self wbuy];
    }
    //    if (self.buyCountTextField.text.length > 0 && [self isNumber] &&[self.buyCountTextField.text intValue] > 0) {
    //        self.board = [GRBsafeKeyBoard GRB_showSafeInputKeyBoard];
    //        __weak typeof(self)weakSelf = self;
    //        self.board.GRBsafeKeyFinish=^(NSString * passWord){
    //            if (passWord.length==6) {
    //
    //                [weakSelf.board GRB_endKeyBoard];
    //                ZZCLog(@"你输入的密码为---%@",passWord);
    //                //在这里判断密码是否正确
    //                if (YES) {
    //                    ZZCLog(@"你输入的密码正确");
    //
    //                }else {
    //                    ZZCLog(@"你输入的密码错误");
    //                }
    //            }
    //
    //        };
    //        self.board.GRBsafeKeyClose=^{
    //
    //            [weakSelf.board GRB_endKeyBoard];
    //        };
    //
    //        self.board.GRBsafeKeyForgetPassWord=^{
    //            ZZCLog(@"点击忘记密码了");
    //
    //        };
    //    }else {
    //        [UIAlertController showInfoAlertLoginVC:self title:@"提示" message:@"你没有输金额数量或输入有误" ok:nil];
    //    }
}

#pragma mark - ---支付宝支付
//- (void)doAlipayPayWithOrderId:(NSString *)orderId orderPayId:(NSString *)orderPayId WIDbody:(NSString *)body WIDsubject:(NSString *)subject show_url:(NSString *)url price:(NSString *)price
- (void)doAlipayPay {
    
    
    //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
    NSString *appScheme = @"alipayZZC";
    
    [[AlipaySDK defaultService] payOrder:_response fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        NSLog(@")))))))))))））））reslut = %@",resultDic);
        if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
            NSLog(@"支付成功");
        }
    }];
    
}
- (void)doAlipayPayWithOrderId:(id)res
{
    
    //重要说明
    //这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
    //真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
    //防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    NSString *appID = @"2017052507339512";
    // 如下私钥，rsa2PrivateKey 或者 rsaPrivateKey 只需要填入一个
    // 如果商户两个都设置了，优先使用 rsa2PrivateKey
    // rsa2PrivateKey 可以保证商户交易在更加安全的环境下进行，建议使用 rsa2PrivateKey
    // 获取 rsa2PrivateKey，建议使用支付宝提供的公私钥生成工具生成，
    // 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
    NSString *rsa2PrivateKey = privateKey;
    NSString *rsaPrivateKey = @"";
    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    //partner和seller获取失败,提示
    if ([appID length] == 0 ||
        ([rsa2PrivateKey length] == 0 && [rsaPrivateKey length] == 0))
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少appId或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order* order = [Order new];
    
    // NOTE: app_id设置
    order.app_id = [NSString stringWithFormat:@"%@",res[@"app_id"]];
    // NOTE: 支付接口名称
    order.method = @"alipay.trade.app.pay";
    
    // NOTE: 参数编码格式
    order.charset = @"utf-8";
    //#warning needUpdate    这里填写回调后台的URL   支付宝同步回调  接口
    //回调后台的URL
    order.notify_url = res[@"notify_url"];
    
    //     NOTE: 当前时间点
    NSDateFormatter* formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    order.timestamp = [formatter stringFromDate:[NSDate date]];
    
    // NOTE: 支付版本
    order.version = @"1.0";
    
    // NOTE: sign_type 根据商户设置的私钥来决定
    order.sign_type = (rsa2PrivateKey.length > 1)?@"RSA2":@"RSA";
    
    // NOTE: 商品数据
    order.biz_content = [BizContent new];
    order.biz_content.body = res[@"biz_content"][@"body"];
    order.biz_content.subject = res[@"biz_content"][@"subject"];
    order.biz_content.out_trade_no = res[@"biz_content"][@"out_trade_no"]; //订单ID（由商家自行制定）
    order.biz_content.timeout_express = @"30m"; //超时时间设置
    order.biz_content.total_amount = [NSString stringWithFormat:@"%.2f",[res[@"total_amount"] floatValue]]; //商品价格
    //将商品信息拼接成字符串
    NSString *orderInfo = [order orderInfoEncoded:NO];
    NSString *orderInfoEncoded = [order orderInfoEncoded:YES];
    NSLog(@"orderSpec = %@",orderInfo);
    // NOTE: 获取私钥并将商户信息签名，外部商户的加签过程请务必放在服务端，防止公私钥数据泄露；
    //       需要遵循RSA签名规范，并将签名字符串base64编码和UrlEncode
    NSString *signedString = res[@"sign"];
    NSLog(@"~~~~~~~~~~~~~~~~~~~%@",signedString);
    RSADataSigner* signer = [[RSADataSigner alloc] initWithPrivateKey:((rsa2PrivateKey.length > 1)?rsa2PrivateKey:rsaPrivateKey)];
    if ((rsa2PrivateKey.length > 1)) {
        signedString = [signer signString:orderInfo withRSA2:YES];
    } else {
        signedString = [signer signString:orderInfo withRSA2:NO];
    }
    NSLog(@"%@",signedString);
    // NOTE: 如果加签成功，则继续执行支付
    if (signedString != nil) {
        //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
        NSString *appScheme = @"alipayZZC";
        
        // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
        //        NSString *orderString = [NSString stringWithFormat:@"%@&sign=%@",
        //                                 orderInfoEncoded, signedString];
        //        NSLog(@"ORDERSTROMG%@",orderString);
        // NOTE: 调用支付结果开始支付
        //快捷订单支付
        [[AlipaySDK defaultService] payOrder:_response fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))reslut = %@",resultDic);
            if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                NSLog(@"支付成功");
            }
        }];
        //        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        //        appDelegate.paySucceed = ^(BOOL isSucceed){
        //            NSURL *URL = [NSURL URLWithString:url];
        //            NSURLRequest *request = [NSURLRequest requestWithURL:URL];
        //            [_webView loadRequest:request];
        //        };
    }
}


//- (void)buy {
//    NSString *token = ZZCNSUserDefaults(@"token");
//    NSLog(@"***************************************%ld",self.arrIndex);
//    if (self.arrIndex == 0) {
//        self.arrIndex = 1;
//    }
//    NSDictionary *dict = @{@"token":token,@"money":@"0.1",@"pay_type":@(3)};
//    NSString *sign = [ZZCRequest getSignWithDict:dict];
//    sign = [NSString md5:[sign lowercaseString]];
//    NSDictionary *param = @{@"timestamp":[NSString timeStr],@"sign":sign,@"token":token,@"money":@"0.1",@"pay_type":@(3)};
//    NSLog(@"----------%@",dict);
//
//    NSLog(@"++++++++++%@",param);
//    [[ZZCRequest sharedNetworkTools] PAYPOST:ZZCURL_API_RECHARGE parameters:param finished:^(id  _Nullable responseObject, NSError * _Nullable error) {
//        if (error) {
//            ZZCLog(@"----------------------------->失败-%@",error);
//        }else {
//
//            ZZCLog(@"->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>%@",_response);
////            [self doAlipayPayWithOrderId:responseObject];
////            if (self.arrIndex == 1) {
////                NSData *strData = responseObject;
////                _response =  [[NSString alloc]initWithData:strData encoding:NSUTF8StringEncoding];
////
//////                [self doAlipayPay];
////            }
//
////            responseObject
////            NSString * _dataString=[NSString stringWithUTF8String:[strr UTF8String]];
//
//        }
//    }];
//}
- (void)buy {
    NSString *token = ZZCNSUserDefaults(@"token");
    NSDictionary *dict = @{@"token":token,@"money":_buyCountTextField.text,@"pay_type":@(1)};
    NSString *sign = [ZZCRequest getSignWithDict:dict];
    sign = [NSString md5:[sign lowercaseString]];
    NSDictionary *param = @{@"timestamp":[NSString timeStr],@"sign":sign,@"token":token,@"money":_buyCountTextField.text,@"pay_type":@(1)};
    [[ZZCRequest sharedNetworkTools] PAYPOST:ZZCURL_API_RECHARGE parameters:param finished:^(id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            ZZCLog(@"失败-%@",error);
        }else {
            ZZCLog(@"-%@",responseObject);
            //            [self buyUib:responseObject];
            NSData *strData = responseObject;
            _response =  [[NSString alloc]initWithData:strData encoding:NSUTF8StringEncoding];
            
            [self doAlipayPay];
            
        }
    }];
}
- (void)wbuy {
    NSString *token = ZZCNSUserDefaults(@"token");
    NSDictionary *dict = @{@"token":token,@"money":_buyCountTextField.text,@"pay_type":@(3)};
    NSString *sign = [ZZCRequest getSignWithDict:dict];
    sign = [NSString md5:[sign lowercaseString]];
    NSDictionary *param = @{@"timestamp":[NSString timeStr],@"sign":sign,@"token":token,@"money":_buyCountTextField.text,@"pay_type":@(3)};
    [[ZZCRequest sharedNetworkTools] POST:ZZCURL_API_RECHARGE parameters:param finished:^(id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            ZZCLog(@"失败-%@",error);
        }else {
            ZZCLog(@"-%@",responseObject);
            [self buyUib:responseObject];
            
        }
    }];
}

- (NSString *)buyUib:(id)res {
    //需要创建这个支付对象
    PayReq *req   = [[PayReq alloc] init];
    //由用户微信号和AppID组成的唯一标识，用于校验微信用户
    req.openID = res[@"appid"];
    
    // 商家id，在注册的时候给的
    req.partnerId = res[@"partnerid"];
    
    // 预支付订单这个是后台跟微信服务器交互后，微信服务器传给你们服务器的，你们服务器再传给你
    req.prepayId  = res[@"prepayid"];
    
    // 根据财付通文档填写的数据和签名
    //这个比较特殊，是固定的，只能是即req.package = Sign=WXPay
    req.package   = res[@"package"];
    
    
    // 随机编码，为了防止重复的，在后台生成
    req.nonceStr  = res[@"noncestr"];
    
    // 这个是时间戳，也是在后台生成的，为了验证支付的
    NSString * stamp = res[@"timestamp"];
    req.timeStamp = stamp.intValue;
    
    // 这个签名也是后台做的
    req.sign = res[@"sign"];
    
    //发送请求到微信，等待微信返回onResp
    [WXApi sendReq:req];
    return @"";
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

//购买方式选择
- (IBAction)buyClick {
    NSArray *arr = @[@"支付宝",@"微信支付"];
    [self.menuView removeFromSuperview];
    self.menuView= [[ZZCMenuView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.buyWayView.frame), ZZCScreenW, 132) contentArray:arr];
    __weak typeof (ZZCMenuView *) weakSelf = self.menuView;
    __weak typeof (self) weakself = self;
    self.menuView.block = ^(BOOL isSeletct ,NSString *title){
        
        [weakSelf removeFromSuperview];
        if (title.length != 0) {
            [weakself.buyWayBtn setTitle:title forState:UIControlStateNormal];
            if ([title isEqualToString:@"支付宝"]) {
                weakself.arrIndex = 1;
            }else if ([title isEqualToString:@"微信支付"]) {
                weakself.arrIndex = 2;
            }
        }
    };
    
    [self.view addSubview:self.menuView];
}

@end
